//
//  GenearchAddViewController.m
//  Eath
//
//  Created by mao on 11/6/14.
//  Copyright (c) 2014 yuhaya. All rights reserved.
//

#import "GenearchAddViewController.h"
#import "Tool.h"
#import "User.h"

@interface GenearchAddViewController ()

@end

@implementation GenearchAddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    CGRect frame = [[UIScreen mainScreen] applicationFrame];
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 30) style:UITableViewStyleGrouped];
    self.table.dataSource = self;
    self.table.delegate = self;
    [self.view addSubview:self.table];
    
    self.photo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"default_head"]];
    self.photo.frame = CGRectMake(240, 20, 60, 60);
    
    CGRect textFrame = CGRectMake(100, 5, 200, 40);
    UIFont * font = [UIFont systemFontOfSize:13];
    
    self.name = [[UITextField alloc] initWithFrame:textFrame];
    self.name.returnKeyType = UIReturnKeyDone;
    self.name.font = font;
    self.name.delegate = self;
    self.name.placeholder = @"输入用户名";
    self.name.textAlignment = NSTextAlignmentRight;
    
    self.full_name = [[UITextField alloc] initWithFrame:textFrame];
    self.full_name.returnKeyType = UIReturnKeyDone;
    self.full_name.font = font;
    self.full_name.delegate = self;
    self.full_name.placeholder = @"输入真实姓名";
    self.full_name.textAlignment = NSTextAlignmentRight;
    
    self.phone = [[UITextField alloc] initWithFrame:textFrame];
    self.phone.returnKeyType = UIReturnKeyDone;
    self.phone.font = font;
    self.phone.delegate = self;
    self.phone.placeholder = @"输入手机号";
    self.phone.textAlignment = NSTextAlignmentRight;
    
    self.card = [[UITextField alloc] initWithFrame:textFrame];
    self.card.returnKeyType = UIReturnKeyDone;
    self.card.font = font;
    self.card.delegate = self;
    self.card.placeholder = @"输入身份证号";
    self.card.textAlignment = NSTextAlignmentRight;
    
    self.relation = [[UITextField alloc] initWithFrame:textFrame];
    self.relation.returnKeyType = UIReturnKeyDone;
    self.relation.font = font;
    self.relation.delegate = self;
    self.relation.placeholder = @"输入与该学生的关系";
    self.relation.textAlignment = NSTextAlignmentRight;
    
    self.pwd = [[UITextField alloc] initWithFrame:textFrame];
    self.pwd.returnKeyType = UIReturnKeyDone;
    self.pwd.font = font;
    self.pwd.delegate = self;
    self.pwd.placeholder = @"输入密码";
    self.pwd.textAlignment = NSTextAlignmentRight;
    
    self.sex = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(220, 10, 80, 30)];
    [self.sex setOnText:@"男"];
    [self.sex setOffText: @"女"];
    
    
    if (self.gen) {
        
        
        self.name.text = self.gen.name;
        self.phone.text = self.gen.phone;
        self.relation.text = self.gen.relation;
        self.card.text = self.gen.card;
        self.photo.image = [UIImage imageNamed:self.gen.photo];
        self.full_name.text = self.gen.full_name;
        if(self.gen.sex == 0){
            self.sex.on = YES;
        }else{
            self.sex.on = NO;
        }
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"更新" style:UIBarButtonItemStyleBordered target:self action:@selector(update)];
        
    }else{
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(save)];
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (self.purpose == 2) {
        if (textField.tag == 5) {
            return YES;
        }else{
            return NO;
        }
        
    }else{
        return YES;
    }
}

- (void)save
{
    if(![User isLogin]){
        
        [Tool showMessage:@"请登录!"];
    }else{
        
        if([self.phone.text isEqualToString:@""]){
            [Tool showMessage:@"请输入手机号!"];
            return;
        }
        NSDictionary * userinfo = [User loginInfo];
        
        NSMutableDictionary * paramter = [NSMutableDictionary dictionary];
        paramter[@"phone"] = self.phone.text;
        paramter[@"par_user_id"] = userinfo[@"id"];
        paramter[@"username"] = self.name.text;
        paramter[@"password"] = self.pwd.text;
        paramter[@"id_card"] = self.card.text;
        paramter[@"gender"] = [NSString stringWithFormat:@"%d",self.sex.on ? 0 : 1];
        paramter[@"name"] = self.full_name.text;
        
        NSString * token = [User token];
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        NSString * url_stus_get = [NSString stringWithFormat:@"%@?token=%@",URL_USER_ADD,token];
        
        [manager POST:url_stus_get parameters:paramter success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSDictionary * redata = responseObject;
//            NSArray * data = redata[@"data"];
            NSString * code = redata[@"code"];
            
            if(code.intValue  == 0){
                
                [Tool showMessage:@"添加成功!"];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else{
                [Tool showMessage:redata[@"msg"]];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [Tool showMessage:[error localizedDescription]];
        }];
    }
    
}

- (void)update
{
    NSMutableDictionary * user = [NSMutableDictionary dictionary];
    user[@"id"] = [NSString stringWithFormat:@"%ld",(long)self.gen.identify];
    user[@"username"] = self.name.text;
    user[@"password"] = self.pwd.text;
    user[@"phone"] = self.phone.text;
    user[@"id_card"] = [self.card.text isEqualToString:@"卡号为空"] ? @"" : self.card.text;
    user[@"gender"] = self.sex.on ? @"0" : @"1";
    user[@"name"] = self.full_name.text;
    
    
    if(![User isLogin]){
        [Tool showMessage:@"请登录!"];
        return;
    }
    NSString * token = [User token];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSString * url_stus_get = [NSString stringWithFormat:@"%@?token=%@",URL_VICE_USER_UPDATE,token];
    [manager POST:url_stus_get parameters:user success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * redata = responseObject;
//        NSArray * data = redata[@"data"];
        NSString * code = redata[@"code"];
        
        if(code.intValue  == 0){
//            DLog(@"%@",data);
            [Tool showMessage:@"修改成功"];
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            [Tool showMessage:redata[@"msg"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Tool showMessage:[error localizedDescription]];
    }];
    
}

-(void) viewWillAppear:(BOOL)animated {
    //注册键盘出现通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];
    [super viewWillAppear:animated];
}

-(void) viewWillDisappear:(BOOL)animated {
    //解除键盘出现通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidShowNotification object:nil];
    //解除键盘隐藏通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidHideNotification object:nil];
    
    [super viewWillDisappear:animated];
}

//自定义键盘打开时触发的事件
-(void) keyboardShow: (NSNotification *)notif {
    
    NSDictionary * info = [notif userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    [UIView animateWithDuration:0.3f animations:^{
//        CGRect curFrame=self.view.frame;
//        curFrame.origin.y = self.table.frame.origin.y - self.height;
//        self.view.frame=curFrame;
        
        CGRect curFrame=self.table.frame;
        curFrame.size.height = [Tool tableHeight] - kbSize.height;
        self.table.frame = curFrame;
    }];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.height = textField.tag * 20;
}

//自定义键盘关闭时触发的事件
-(void) keyboardHide: (NSNotification *)notif {
    [UIView animateWithDuration:0.3f animations:^{
//        CGRect curFrame=self.view.frame;
//        CGRect status = [[UIApplication sharedApplication] statusBarFrame];
//        curFrame.origin.y = self.navigationController.navigationBar.frame.size.height + status.size.height;
//        self.view.frame=curFrame;
        
        CGRect curFrame=self.table.frame;
        curFrame.size.height = [Tool tableHeight] - 30;
        self.table.frame = curFrame;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.purpose == 2) {
        return 6;
    }else{
        return 7;
    }
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [[UITableViewCell alloc] init];
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 50)];
    label.font = [UIFont systemFontOfSize:14];
    NSString * label_name;
    
    switch (indexPath.row) {
        case 0:
            label_name = @"头像";
            label.frame = CGRectMake(15, 0, 100, 100);
            self.photo.tag = indexPath.row;
            [cell.contentView addSubview:self.photo];
            break;
            
        case 1:
            label_name = @"用户名";
            self.name.tag = indexPath.row;
            [cell.contentView addSubview:self.name];
            break;
            
        case 2:
            label_name = @"身份证号";
            self.card.tag = indexPath.row;
            [cell.contentView addSubview:self.card];
            break;
            
        case 3:
            label_name = @"手机号";
            self.phone.tag = indexPath.row;
            [cell.contentView addSubview:self.phone];
            break;
            
        case 4:
            label_name = @"密码";
            self.pwd.tag = indexPath.row;
            [cell.contentView addSubview:self.pwd];
            break;
            
        case 5:
            label_name = @"真实姓名";
            self.full_name.tag = indexPath.row;
            [cell.contentView addSubview:self.full_name];
            break;
            
        case 6:
            label_name = @"性别";
            self.sex.tag = indexPath.row;
            [cell.contentView addSubview:self.sex];
            break;
            
        case 7:
            label_name = @"学生的关系";
            self.relation.tag = indexPath.row;
            [cell.contentView addSubview:self.relation];
            break;
            
        
            
        default:
            break;
    }
    label.text = label_name;
    [cell.contentView addSubview:label];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 100;
    }else{
        return 50;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return NO;
}
@end
